#include <i386/stdlib.h>
#include <i386/string.h>
#include <i386/limits.h>
#include <stdarg.h>
#include <ctype.h>

long int strtoi(char *s, int base, char **scan_end) {
    int sign = 1, value, overflow = 0;
    long int result = 0, oldresult;
    
    // check for an explicit sign
    if (*s == '-') {
		sign = -1;
		s++;
    } else if (*s == '+') {
		s++;
    }
    
    // skip leading zeros
    while (*s == '0') {
    	s++;
    }
    
    // scan through the digits and accumulate powers of base
    while (isnumber(*s, base)) {
		value = tonumber(*s++);
		
		if (value > base || value < 0) {
			return 0;
		}
		
		oldresult = result;
		result *= base;
		result += value;
		
		// check for overflow
		if (oldresult > result) {
			overflow = 1;
		}
    }
    
    if (scan_end != 0) {
    	*scan_end = s;
    }
    
    if (overflow) {
    	result = INT_MAX;
    }
    
    result *= sign;
    return result;
}
